package xyz.zhno.template.common.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * RedisTemplate序列化配置
 * @author zh_o
 */
public class RedisConfig {

    /**
     * JSON序列化
     * Key: String
     * Value: JSON
     */
    @Bean(name = "jsonRedisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // 字符串序列化
        StringRedisSerializer sr = new StringRedisSerializer();
        // Json序列化
        Jackson2JsonRedisSerializer<Object> jr = new Jackson2JsonRedisSerializer<>(Object.class);
        // 解决序列化LocalDateTime报错
        jr.setObjectMapper(
                new ObjectMapper()
                        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                        .registerModule(new JavaTimeModule())
        );
        // 设置序列化方式
        redisTemplate.setKeySerializer(sr);
        redisTemplate.setValueSerializer(jr);
        redisTemplate.setHashKeySerializer(sr);
        redisTemplate.setHashValueSerializer(jr);
        return redisTemplate;
    }

}
